<template>
    <div class="container">
        <Alert type="error" show-icon>
            <div style="color: red; font-size: 18px; font-weight: 600;">
                注意：二维码下载后张贴前请先行确认其有效性(扫码后在场所统计中查看数量是否变化)，如有问题请及时联系！
            </div>
         <!--   <template slot="desc">
                <div>由于二维码生成量大，12点前添加的数据会在13点后生成二维码、12点后17点前添加的数据会在18点后生成二维码！</div>
            </template>-->
        </Alert>
        <Alert>
            <Form :model="searchObj" inline>
                <FormItem>
                    <Input v-model="searchObj.place_name" class="search-input" clearable placeholder="请输入场所名称"/>
                </FormItem>
                <FormItem>
                    <Input v-model="searchObj.area" class="search-input" clearable placeholder="请输入区、县（市）"/>
                </FormItem>
                <FormItem>
                    <Input v-model="searchObj.street" class="search-input" clearable placeholder="请输入街道"/>
                </FormItem>
                <FormItem>
                    <Input v-model="searchObj.community" class="search-input" clearable placeholder="请输入社区"/>
                </FormItem>
                <FormItem>
                    <Input v-model="searchObj.remarks" class="search-input" clearable placeholder="请输入备注"/>
                </FormItem>
                <!--<FormItem>
                    <Input v-model="searchObj.place_type" class="search-input" clearable placeholder="请输入场所类别"/>
                </FormItem>-->
                <FormItem>
                    <Select v-model="searchObj.place_type" placeholder="请选择场所类别" clearable filterable
                            style="width: 200px">
                        <Option v-for="item in placeTypeList"
                                :value="item.value"
                                :key="item.value">{{ item.name }}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem>
                    <Select v-model="searchObj.code" placeholder="请选择机构" clearable filterable style="width: 200px">
                        <Option v-for="item in organizationList"
                                :value="item.code"
                                :key="item.code">{{ item.name }}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem>
                    <Button class="search-btn" type="primary" @click="searchAction">
                        <Icon type="ios-search"/>
                        搜索
                    </Button>
                </FormItem>
            </Form>
            <Divider/>
            <Form :model="searchObj" inline>
                <FormItem>
                    <Button class="search-btn" type="primary" @click="addAction">
                        <Icon type="ios-add"/>
                        添加
                    </Button>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="importExcel">
                        <Icon type="ios-cloud-upload-outline"/>
                        数据导入
                    </Button>
                </FormItem>
                <FormItem>
                    <Button class="search-btn" type="primary" @click="downloadSelect">
                        <Icon type="ios-cloud-download-outline"/>
                        批量下载二维码
                    </Button>
                </FormItem>
                <FormItem>
                    <Button class="search-btn" type="error" @click="delPLAction">
                        <Icon type="md-close"/>
                        批量删除
                    </Button>
                </FormItem>
                <FormItem>
                    <Button  class="search-btn" type="warning" @click="resetAction">
                        <Icon type="md-refresh"/>
                        重置二维码
                    </Button>
                  <!--  <Tooltip :content="toolpText" placement="right">
                        <Icon type="md-help-circle" class="tooltip-style"/>
                    </Tooltip>-->
                </FormItem>
            </Form>
        </Alert>
        <Row>
            <vxe-toolbar custom></vxe-toolbar>
            <vxe-table
                    ref="xTable"
                    border
                    resizable
                    highlight-hover-row
                    height="500"
                    size="medium"
                    show-overflow="tooltip"
                    :loading="tableLoading"
                    align="center"
                    header-align="center"
                    @checkbox-all="selectAllEvent"
                    @checkbox-change="selectChangeEvent"
                    :sort-config="{trigger: 'cell'}"
                    :data="tableData">
                <vxe-table-column type="checkbox" width="60"></vxe-table-column>
                <vxe-table-column type="seq" title="#" width="60"></vxe-table-column>
                <vxe-table-column :field="item.key" :title="item.title" min-width="120"
                                  v-for="(item,index) in tableColumns" :key="index">
                </vxe-table-column>
                <vxe-table-column field="action" title="操作" width="450">
                    <template v-slot="{row}">
                        <ButtonGroup>
                            <!--<Button type="warning" size="small" class="action-btn"
                                    @click="bindAction(row)">授权人员
                            </Button>-->
                            <Button type="success" size="small" class="action-btn"
                                    @click="qrcodeAction(row)">下载二维码
                            </Button>
                            <Button type="primary" size="small" class="action-btn"
                                    @click="editAction(row)">编辑修改
                            </Button>
                            <Button type="info" size="small" class="action-btn"
                                    @click="infoAction(row)">查看详情
                            </Button>
                            <Button v-has="'View_data'" type="warning" size="small" class="action-btn"
                                    @click="ViewAction(row)">查看人员数据
                            </Button>
                            <Button type="error" size="small" class="action-btn"
                                    @click="delAction(row.id)">删除
                            </Button>
                        </ButtonGroup>
                    </template>
                </vxe-table-column>
            </vxe-table>
        </Row>
        <br>
        <Row type="flex" justify="end">
            <Page show-sizer show-total :current="pageObj.pageNo" :page-size="pageObj.pageSize"
                  :total="pageObj.totalRecord"
                  @on-change="getPageNo" :page-size-opts="[10,20,50,100]" @on-page-size-change="pageSizeChange"/>
        </Row>
        <br>
        <option-modal ref="optionModal" :modal-title="modalTitle" :modal-show="modalShow" :modal-type="modalType"
                      :modalWidth="modalWidth" :dataObj="modalData" @cancelOption="cancelOption"
                      @saveOption="saveOption"></option-modal>
        <Modal style="text-align: center" v-model="downImgModel" width="360">
            <p slot="header" style="color:#f60;text-align:center">
                <Icon type="ios-information-circle"></Icon>
                <span>确认下载选中场所二维码吗？</span>
            </p>
            <div style="text-align:center">
                批量下载图片很慢，请不要关闭浏览器，耐心等待<br>
                {{ downNowName }}
            </div>
            <img id="canvas" :src="datasrc" style="width:100%;height: 200px;"></img>
            <RadioGroup v-model="downloadType" type="button">
                <Radio label="horizontal">横版</Radio>
                <Radio label="vertical">竖版</Radio>
                <Radio label="default">全部</Radio>
            </RadioGroup>
            <div slot="footer">
                <Button type="error" size="large" long :loading="downLoading" @click="startDownAction">确认下载</Button>
            </div>
        </Modal>
        <Modal style="text-align: center" v-model="resetModel" width="360">
            <p slot="header" style="color:#f60;text-align:center">
                <Icon type="ios-information-circle"></Icon>
                <span>确认重置为有编号的二维码么？</span>
            </p>
            <div style="text-align:center">
                此操作会将机构下所有二维码信息清空，系统后台将持续为您生成新的二维码...<br>
            </div>
            <div style="width: 100%;height: 200px; text-align: center;margin-bottom: 10px;">
                <img v-if="downloadType == 'horizontal'" src="@/assets/images/qr_code_demo_h.png"
                     style="width:100%;height: 200px;"/>
                <img v-if="downloadType == 'vertical'" src="@/assets/images/qr_code_demo_v.png" style="height: 200px;"/>
            </div>
            <RadioGroup v-model="downloadType" type="button">
                <Radio label="horizontal">横版</Radio>
                <Radio label="vertical">竖版</Radio>
                <Radio label="default">全部</Radio>
            </RadioGroup>
            <div slot="footer">
                <Button type="error" size="large" long :loading="resetLoading" @click="startResetAction">确认重置</Button>
            </div>
        </Modal>
        <Modal v-model="delMultiModal" width="360">
            <p slot="header" style="color:#f60;text-align:center">
                <Icon type="information-circled"></Icon>
                <span>删除确认</span>
            </p>
            <div style="text-align:center">
                <p>此任务将删除{{this.num.length}}条数据</p>
                <p>是否继续删除？</p>
            </div>
            <div slot="footer">
                <Button type="error" size="large" long :loading="delMultiLoading" @click="delSubmit">删除</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import {
  updatePlaceURL,
  getPeopleList,
  deletePlace,
  findOfficeXJList,
  deletePlacePL,
  rebootCreateQrCode
  // userStrToQrcode
  // getPlaceCount
} from '@/api/pass'
import OptionModal from './components/option-modal'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import dict from '@/libs/dict'

export default {
  components: { OptionModal },
  data () {
    return {
      delMultiLoading: false,
      delMultiModal: false,
      modalShow: false,
      modalTitle: '',
      modalWidth: 500,
      modalType: '',
      num: [],
      modalData: {},
      tableColumns: [
        {
          title: '场所名称',
          key: 'place_name',
          tooltip: true,
          width: 300,
          align: 'center'
        },
        {
          title: '联系人姓名',
          width: 150,
          tooltip: true,
          key: 'name',
          align: 'center'
        },
        {
          title: '联系电话',
          width: 150,
          tooltip: true,
          key: 'mobile',
          align: 'center'
        }
      ],
      tableData: [],
      selectData: [],
      tableLoading: false,
      pageObj: {
        pageNo: 1,
        pageSize: 20,
        totalRecord: 0
      },
      searchObj: {},
      datasrc: null,
      resetModel: false,
      resetLoading: false,
      downImgModel: false,
      downLoading: false,
      downNowName: '',
      selectList: [],
      organizationList: [],
      placeTypeList: dict.placeCategory,
      downloadType: 'default',
      toolpText: '仅在当日17:00至次日8:00可以重置'
    }
  },
  props: {},
  mounted () {
    this.init()
    this.findOfficeXJList()
  },
  computed: {
    company_code () {
      return this.$store.state.user.severUserInfo.data.company_code
    }
  },
  methods: {
    delSubmit () {
      this.delMultiLoading = true
      deletePlacePL({ dataList: this.num }).then(res => {
        let data = res.data
        if (data.errcode === 0) {
          this.init()
          this.delMultiLoading = false
          this.delMultiModal = false
          this.success('删除成功')
        } else {
          this.error(data)
        }
      })
    },
    selectAllEvent (row) {
      this.num = row.selection
    },
    delPLAction () {
      if (this.num.length <= 0) {
        this.$Message.error('请选择要删除的数据')
      } else {
        this.delMultiModal = true
      }
    },
    selectChangeEvent (row) {
      this.num = row.selection
      // console.log(row.selection)
    },
    findOfficeXJList () {
      // let company_name = this.$store.state.user.severUserInfo.data.company_name
      // this.organizationList.push({
      //   name: company_name,
      //   code: ''
      // })
      findOfficeXJList().then(ret => {
        const data = ret.data
        if (data.errcode === 0) {
          data.data.forEach(item => {
            this.organizationList.push(item)
          })
        } else {
          this.error(data)
        }
      })
    },
    downImg (arr, imgNameList) {
      let _this = this
      let blogTitle = '打包图片'
      switch (this.downloadType) {
        case 'horizontal':
          blogTitle = '横版打包图片'
          break
        case 'vertical':
          blogTitle = '竖版打包图片'
          break
      }
      let zip = new JSZip()
      let imgs = zip.folder(blogTitle)
      let baseList = []
      // let imgNameList = ['图片1', '图片2', '图片3']
      // let arr = ['http://sstpw.tripln.top/wl/downQrCodeImg?name=a7381e02-6cd1-11ea-b1d1-0242ac110004&type=1', 'http://sstpw.tripln.top/wl/downQrCodeImg?name=a7381e02-6cd1-11ea-b1d1-0242ac110004&type=1']
      // 递归写法
      function preload (arr, index) {
        // console.log('当前图片：', arr)
        index = index || 0
        if (index >= arr.length) {
          return false
        }
        if (arr && arr.length > index) {
          let img = new Image()
          img.onload = function () {
            let image = new Image()
            // 解决跨域 Canvas 污染问题
            image.setAttribute('crossOrigin', 'anonymous')

            image.onload = function () {
              let canvas = document.createElement('canvas')
              canvas.width = image.width
              canvas.height = image.height

              let context = canvas.getContext('2d')
              context.drawImage(image, 0, 0, image.width, image.height)

              let url = canvas.toDataURL() // 得到图片的base64编码数据
              _this.datasrc = url
              _this.downNowName = imgNameList[index] + '正在下载'
              canvas.toDataURL('image/png')
              baseList.push(url.substring(22)) // 去掉base64编码前的 data:image/png;base64,
              if (baseList.length === arr.length && baseList.length > 0) {
                for (let k = 0; k < baseList.length; k++) {
                  imgs.file(imgNameList[k] + '.png', baseList[k], { base64: true })
                }
                _this.downNowName = '打包压缩中...'
                zip.generateAsync({ type: 'blob' }).then(function (content) {
                  // see FileSaver.js
                  FileSaver.saveAs(content, blogTitle + '.zip')
                  _this.downLoading = false
                  _this.downImgModel = false
                  console.log('结束时间：', _this.$common.xeUtils.toDateString(new Date()))
                })
              }
            }
            image.src = arr[index]
            // console.log('当前src', arr[index])
            preload(arr, index + 1)
          }
          img.src = arr[index]
        }
      }
      preload(arr)
      // 普通写法(废弃 --- 异步调用会产生数据错乱的问题)
      // for (let i = 0; i < arr.length; i++) {
      //   // (function (i) {
      //   let image = new Image()
      //   // 解决跨域 Canvas 污染问题
      //   image.setAttribute('crossOrigin', 'anonymous')
      //
      //   image.onload = function () {
      //     let canvas = document.createElement('canvas')
      //     canvas.width = image.width
      //     canvas.height = image.height
      //
      //     let context = canvas.getContext('2d')
      //     context.drawImage(image, 0, 0, image.width, image.height)
      //
      //     let url = canvas.toDataURL() // 得到图片的base64编码数据
      //     _this.datasrc = url
      //     _this.downNowName = imgNameList[i] + '正在下载'
      //     canvas.toDataURL('image/png')
      //     baseList.push(url.substring(22)) // 去掉base64编码前的 data:image/png;base64,
      //     if (baseList.length === arr.length && baseList.length > 0) {
      //       for (let k = 0; k < baseList.length; k++) {
      //         imgs.file(imgNameList[k] + '.png', baseList[k], { base64: true })
      //       }
      //       console.log('img:', imgs)
      //       zip.generateAsync({ type: 'blob' }).then(function (content) {
      //         // see FileSaver.js
      //         FileSaver.saveAs(content, blogTitle + '.zip')
      //         _this.downLoading = false
      //         _this.downImgModel = false
      //         console.log('结束时间：', _this.$common.xeUtils.toDateString(new Date()))
      //       })
      //     }
      //   }
      //   image.src = arr[i]
      //   console.log('当前src', arr[i])
      //   // })(i)
      // }
    },
    importExcel () {
      this.$router.push({
        name: 'placeExcel',
        query: { type: 'place' }
      })
    },
    cancelOption () {
      this.modalShow = false
    },
    saveOption () {
      this.modalShow = false
      this.init()
    },
    success (val) {
      val = this.$common.xeUtils.isEmpty(val) ? '操作成功' : val
      this.$Message.success(val)
    },
    error (data) {
      this.$Message.error({
        content: '操作失败,\n' + data.errmsg
      })
    },
    getPageNo (pageNo) {
      this.pageObj.pageNo = pageNo
      this.init()
    },
    pageSizeChange (e) {
      this.pageObj.pageSize = e
      this.init()
    },
    tableSelectChange (val) {
      this.selectData = val
    },
    initPage () {
      this.pageObj.pageNo = 1
      // this.pageObj.pageSize = 20
    },
    init (data) {
      const obj = {
        pageNo: this.pageObj.pageNo,
        pageSize: this.pageObj.pageSize,
        place_name: this.$common.xeUtils.trim(this.searchObj.place_name),
        code: this.$common.xeUtils.trim(this.searchObj.code),
        name: this.$common.xeUtils.trim(this.searchObj.name),
        mobile: this.$common.xeUtils.trim(this.searchObj.mobile),
        area: this.$common.xeUtils.trim(this.searchObj.area),
        street: this.$common.xeUtils.trim(this.searchObj.street),
        community: this.$common.xeUtils.trim(this.searchObj.community),
        remarks: this.$common.xeUtils.trim(this.searchObj.remarks),
        // place_address: this.$common.xeUtils.trim(this.searchObj.place_address),
        place_type: this.$common.xeUtils.trim(this.searchObj.place_type)
      }
      let param = data || obj
      this.tableLoading = true
      getPeopleList(param).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.tableLoading = false
          this.tableData = data.data.results
          this.pageObj.totalRecord = data.data.totalRecord
        } else {
          this.tableLoading = false
          this.error(data)
        }
      })
    },
    searchAction () {
      this.initPage()
      this.init()
    },
    addAction () {
      this.modalTitle = '添加'
      this.modalType = 'add'
      this.modalWidth = 650
      this.modalData = {}
      this.modalShow = true
    },
    editAction (val) {
      this.modalTitle = '编辑修改'
      this.modalType = 'edit'
      this.modalWidth = 650
      this.modalData = this.$common.xeUtils.clone(val)
      this.modalShow = true
    },
    infoAction (val) {
      this.modalTitle = '查看详情'
      this.modalType = 'info'
      this.modalWidth = 800
      this.modalData = this.$common.xeUtils.clone(val)
      this.$refs.optionModal.getBindList(val)
      this.modalShow = true
    },
    delAction (val) {
      this.$Modal.confirm({
        title: '确认删除么？',
        content: '请仔细核对后再操作',
        loading: true,
        onOk: () => {
          this.deleteOne(val)
        }
      })
    },
    ViewAction (row) {
      console.log(row, '查看详情')
      this.$router.push({
        path: '/place/view',
        query: {
          verification_code: row.verification_code
        }
      })
    },
    // 修改二维码字段
    updatePlaceURLAction (val, url) {
      updatePlaceURL({ id: val.id, qr_code: url }).then(ret => {
        const data = ret.data
        if (data.errcode === 0) {
          val.qr_code = url
          window.location.href = url
        } else {
          this.error(data)
        }
      })
    },
    // 绑定人员
    bindAction (val) {
      this.modalTitle = '授权人员'
      this.modalType = 'bind'
      this.modalWidth = 650
      this.modalData = this.$common.xeUtils.clone(val)
      this.$refs.optionModal.getBindList(val)
      this.modalShow = true
    },
    // 二维码
    qrcodeAction (row) {
      if (row.qr_code) {
        // console.log('二维码地址', row.qr_code)
        let codeArr = row.qr_code.split(',')
        // let url = 'http://sstpw.tripln.top/wl/userStrToQrcode?name=' + row.id + '&encryption=' + row.verification_code + '&downName=' + row.place_name
        if (this.company_code === 'LA00014') {
          const url = codeArr[0]
          // url = url + '&type=2'
          // this.updatePlaceURLAction(row, url)
          window.location.href = url
        } else {
          this.modalTitle = '选择二维码进行下载'
          this.modalType = 'qrcode'
          // this.modalData = { url: url = url + '&type=' }
          this.modalData = { url: codeArr, place_name: row.place_name }
          this.modalShow = true
        }
      } else {
        this.$Message.error('二维码信息为空！')
      }
    },
    downloadSelect () {
      this.selectList = this.$refs.xTable.getCheckboxRecords()
      if (this.selectList.length <= 0) {
        this.$Message.error('请选择要下载的数据')
        return false
      }
      this.downImgModel = true
    },
    resetAction () {
      this.resetModel = true
    },
    startResetAction () {
      const param = {}
      switch (this.downloadType) {
        case 'horizontal':
          param.type = 6
          break
        case 'vertical':
          param.type = 7
          break
        case 'default':
          param.type = 8
          break
      }
      this.resetLoading = true
      rebootCreateQrCode(param).then(res => {
        let data = res.data
        if (data.errcode === 200) {
          this.success('操作成功，共更新了' + data.data + '家场所')
          this.resetLoading = false
          this.resetModel = false
          this.init()
        } else {
          this.resetLoading = false
          this.error(data)
        }
      })
    },
    startDownAction () {
      console.log('开始时间：', this.$common.xeUtils.toDateString(new Date()))
      this.downLoading = true
      this.downNowName = '组装数据中...'
      let dataArr = []
      let dataNameArr = []
      switch (this.downloadType) {
        case 'horizontal':
          this.selectList.forEach((item) => {
            if (item.qr_code) {
              item.qr_code_arr = item.qr_code.split(',')
              // console.log('--', item.qr_code_arr)
              item.qr_code_arr.forEach((item2, index) => {
                const lastChar = item2.substr(item2.lastIndexOf('&type=') + 6, 1)
                if (lastChar === '1' || lastChar === '6') {
                  dataArr.push(item2)
                  dataNameArr.push(item.place_name + '-' + (index + 1))
                }
              })
            }
          })
          break
        case 'vertical':
          this.selectList.forEach((item) => {
            if (item.qr_code) {
              item.qr_code_arr = item.qr_code.split(',')
              // console.log('--', item.qr_code_arr)
              item.qr_code_arr.forEach((item2, index) => {
                const lastChar = item2.substr(item2.lastIndexOf('&type=') + 6, 1)
                if (lastChar === '4' || lastChar === '7') {
                  dataArr.push(item2)
                  dataNameArr.push(item.place_name + '-' + (index + 1))
                }
              })
            }
          })
          break
        case 'default':
          this.selectList.forEach((item) => {
            if (item.qr_code) {
              item.qr_code_arr = item.qr_code.split(',')
              item.qr_code_arr.forEach((item2, index) => {
                dataArr.push(item2)
                dataNameArr.push(item.place_name + '-' + (index + 1))
              })
            }
          })
          break
      }
      // console.log(dataArr, '---', dataNameArr)
      const itemDownData = [dataArr, dataNameArr]
      this.downImg(itemDownData[0], itemDownData[1])
    },
    deleteOne (val) {
      deletePlace({ id: val }).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.$Modal.remove()
          this.init()
          this.success('删除成功')
        } else {
          this.$Modal.remove()
          this.error(data)
        }
      })
    }
  }

}
</script>

<style scoped>
    .tooltip-style{
        margin-left: 10px;
        color: orange;
        cursor: pointer;
    }
    .container {
        padding-bottom: 50px;
    }

    .action-btn {
        margin-right: 5px;
        /*margin-bottom: 5px;*/
    }

    .search-input {
        /*width: 180px;*/
    }

    .search-btn {
        /*width: 100px;*/
    }

    /deep/ .ivu-divider-horizontal {
        margin: 12px 0;
    }

    /deep/ .ivu-form-item {
        margin-bottom: 6px;
    }

    /deep/ .ivu-btn-group .ivu-btn {
        border-radius: 3px !important;
    }
</style>
